(function() {
  app.controller('strategyCtrl', function($stateParams, $interval, $scope, $rootScope, bottomdilog, tradeApi, alertTip, $state, quoteApi, kchart, local_m, $timeout, centerdilog) {
    var selected = local_m.get('selected_strategy_options') || {}; // 首页创建动态 选项
    var code_info = $scope.storage.local('detail_codeinfo');
    var type_yiyuan = $stateParams.type; // 是否是从一元体验进入的标识
    var pay_id = '1';

    if (type_yiyuan === 'free-wx' || type_yiyuan === 'free-pc') {
      pay_id = '10';
    } else if (type_yiyuan === 'yiyuan') {
      pay_id = '11';
    }
    $scope.start = function() {
      if (pay_id === '1') {
        tradeApi
          .query({
            funcId: '300036',
            data: {}

          })
          .then(function(res) {
            if (!res) return;
            var tpl = '<p style="margin-bottom:0.1rem;" pay-id="1">普通支付<p>';
            for (var i = 0; i < res.length; i++) {
              if (res[i].pay_id === '11' || res[i].pay_id === '10' || res[i].coupon_count === '0') {
                res.splice(i, 1);
                i--;
              }
            }
            if (res.length <= 0) return;
            res.push({ pay_name: '普通支付', pay_id: '1' });

            centerdilog
              .open({
                ok: function() {
                  $state.go('home');
                },
                tpl: '<p style="margin-bottom:0.1rem;"  ng-repeat="it in res track by $index" ng-bind="it.pay_name" ng-click="item_click(it)"><p>',
                tpl_scope: {
                  res: res,
                  item_click: function(it) {
                    pay_id = it.pay_id;
                    $scope.init();
                    centerdilog.view = false;
                  }
                },
                cancel_hiden: false,
                oktxt: '点击这里返回首页',
              });
          });
        return;
      }

      tradeApi
        .query({
          funcId: '300036',
          data: {
            pay_id: pay_id,
          }
        })
        .then(function(res) {
          if (!res || res[0].coupon_count === '0') {
            centerdilog
              .open({
                msg: '您暂无体验机会',
                ok: function() {
                  $state.go('home');
                },
                cancel_hiden: false,
                oktxt: '点击这里返回首页',
              });
          }
        });
    };


    $scope.init = function() {
      $scope.code_info = {
        product_code: code_info.code,
        product_name: code_info.name,
        market: code_info.market
      };

      tradeApi
        .query({ // 查询股票信息
          funcId: '000001',
          data: {
            product_code: code_info.code
          }
        })
        .then(function(res) {
          $scope.code_info.last_price = res[0].last_price;
          return tradeApi
            .query({
              funcId: '000002',
              data: {
                product_type: 0,
                pay_id: pay_id
              }
            });
        })
        .then(function(res) {
          if (!res || res.length === 0) return;
          $scope.list = res;
          var i = '0';
          var j = '0';
          angular.forEach(res, function(item, index) {
            if (item.borrow_balance === selected.borrow_balance) {
              i = index;
            }
          });
          angular.forEach(res[i].sub, function(item, index) {
            if (item.deposit_balance === selected.deposit_balance) {
              j = index;
            }
          });
          $scope.cash(i); // 初始选中第一个
          $scope.strate_tab(j);
        });

      tradeApi
        .query({
          funcId: '300004',
          data: {}
        })
        .then(function(res) {
          $scope.code_info.enable_balance = res.enable_balance;
        });
    };

    $scope.cash = function(index) { // 选策略执行金
      $scope.strate_num_actived = index;
      $scope.sub = $scope.list[index].sub;
      $scope.strate_tab('0');
    };

    $scope.strate_tab = function(index) { // 选保障金
      $scope.strate_tab_actived = index;
      $scope.sub_actived = $scope.sub[index];
      console.log($scope.sub_actived)
      $scope.enable_buy = $scope.code_info.last_price > 0 ? Math.floor(($scope.sub_actived.borrow_balance / $scope.code_info.last_price) / 100) * 100 : 0;
      $scope.use_rate = $scope.enable_buy * $scope.code_info.last_price / $scope.sub_actived.borrow_balance;

      $scope.fare = {};
      $scope.fare.trade_fare = $scope.sub_actived.fare;
      $scope.fare.deposit_balance = $scope.sub_actived.deposit_balance;
      $scope.tol_fare = parseFloat($scope.fare.deposit_balance) + parseFloat($scope.fare.trade_fare);
    };
    $scope.ok_comfirm = function() {
      if ($scope.enable_buy < 100 || !$scope.enable_buy) return;
      if (!$scope.readed) {
        centerdilog
          .open({
            msg: '请必须同意《合作协议》才能创建策略',
            cancel_hiden: true,
            oktxt: '关闭'
          });
        return;
      }

      bottomdilog
        .open({
          type: '2',
          title: '请选择业务类型',
          list: [{ txt: '立即创建策略', id: '1' }, { txt: '添加条件单', id: '2' }],
          list_click: function(it, index) {
            if (it.id === '1') {
              $scope.create_req();
            } else if (it.id === '2') {
              $state.go('condition', {
                type: '1',
                data: {
                  borrow_balance: $scope.sub_actived.product_name,
                  deposit_balance: $scope.sub_actived.deposit_balance,
                  fare: $scope.sub_actived.fare,
                  prodcut_id: $scope.sub_actived.product_id,
                  product_code: $scope.code_info.product_code,
                  product_name: $scope.code_info.product_name,
                  market: $scope.code_info.market,
                }
              })
            }
          }
        });

    }
    $scope.create_req = function() {
      centerdilog
        .open({
          msg: '确定创建该策略？',
          ok: $scope.request,
        });
    };

    $scope.request = function() {
      if ($scope.enable_buy < 100) return;
      tradeApi
        .query({
          funcId: '300025',
          data: {
            prodcut_id: $scope.sub_actived.product_id,
            product_code: $scope.code_info.product_code,
            product_name: $scope.code_info.product_name,
            market: $scope.code_info.market,
            pay_id: pay_id,
            entrust_price: $scope.code_info.last_price
          }
        })
        .then(function(res) {
          if (!res.entrust_no) return;

          if (pay_id === '11') { // 一元体验
            $state.go('running', { tab_index: '2' });
          } else if (pay_id === '10') { // 点击和讯免费体验来的用户
            centerdilog
              .open({
                cancel_hiden: false,
                oktxt: '点击这里查看您创建的策略',
                tpl: '<div><img src="img/yiyuan-code.png" id="go-to-code-help"/><p style="font-weight:700">点击二维码关注我们</p></div>',
                ok: function() {
                  $state.go('running', { tab_index: '2' });
                },
                tpl_cb: function() {
                  $('#go-to-code-help').on('click', function() {
                    $state.go('wx-focus');
                  });
                }
              });
          } else {
            alertTip.open({
              msg: '买入指令发布成功',
              state: 1
            });
            // centerdilog
            //   .open({
            //     msg: 'WOW ！您的策略创建成功了',
            //     closetxt: '去看看我的策略',
            //     cancel: function() {
            //       $state.go('running', { tab_index: '2' });
            //     },
            //     oktxt: '再创建一条',
            //   });
          }
        });
    };

    $scope.reload = function() {
      tradeApi
        .query({ // 查询股票信息
          funcId: '000001',
          data: {
            product_code: code_info.code
          }
        })
        .then(function(res) {
          $scope.code_info.last_price = res[0].last_price;
        });

      tradeApi
        .query({ // 余额
          funcId: '300004',
          data: {}
        }).then(function(res) {
          $scope.code_info.enable_balance = res.enable_balance;
        });
    };

    var timer = $interval(function() {
      $scope.reload();
    }, 3000);

    $scope.$on('$destroy', function() {
      $interval.cancel(timer);
      timer = null;
    });
    $scope.go_to_hezuo = function() {
      var data = angular.copy($scope.sub_actived);
      data.product_name = $scope.code_info.product_name;
      $state.go('hezuo-agree', { data: data, type: 'strategy' })
    }
  });
})();